package com.ocom.mqsimple.business.allperson;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.dto.GetMealTimeDto;
import com.ocom.common.entity.card.EntityNotMealRecode;
import com.ocom.common.entity.payconfig.EntityXfMealLeave;
import com.ocom.common.request.payconfig.GetOrderMealLeaveRequest;
import com.ocom.common.request.simple.AllPersonRequest;
import com.ocom.common.request.web.ConsTimeConfigOnShowRequest;
import com.ocom.common.request.wx.UserAccessPageSetAccessRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.vo.human.UserInfoYkmVo;
import com.ocom.mqsimple.business.access.AccessProductService;
import com.ocom.mqsimple.config.AllPersonConfig;
import com.ocom.mqsimple.feign.AccessClientService;
import com.ocom.mqsimple.feign.HumanClientService;
import com.ocom.mqsimple.feign.PayConfigClientService;
import com.ocom.mqsimple.feign.XfRecordFeign;
import com.ocom.redis.util.RedisUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class AllPersonMqListener {

	private Logger logger = LoggerFactory.getLogger(AllPersonMqListener.class);


	@Resource
	RedisUtil redisUtil;


	@Autowired
	AccessClientService accessClientService;


	@Autowired
	private AccessProductService accessProductService;

	@Autowired
	private HumanClientService humanClientService;

	@Autowired
	private PayConfigClientService payConfigClientService;

	@Autowired
	private XfRecordFeign xfRecordFeign;

	/**
	 * 把该监听命名为A监听
	 * 监听队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 *
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues = AllPersonConfig.ALL_PERSON_QUEUE)
	public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		logger.info("AllPerson 消费中");
		logger.info("message【{}】", message);
		String humanMessage = new String(message.getBody(), StandardCharsets.UTF_8);
		//TODO 数据库操作样例
		logger.info("AllPerson-start:【{}】", humanMessage);
		logger.info("System.currentTimeMillis()【{}】", System.currentTimeMillis());


		AllPersonRequest request = JSON.parseObject(humanMessage,AllPersonRequest.class);

//		System.out.println(request);


		try {
			//查人数
			Map<String, Object> map3 = new HashMap<>();
			map3.put("comId", request.getComId());
			map3.put("page", 1);
			map3.put("size", 1);
			Result result2 = humanClientService.PersonnelGetPersonInfo(map3);
			JSONObject jsonObject  = JSON.parseObject(JSON.toJSONString(result2.getData()));

			Integer total = jsonObject.getInteger("total");

			//找不到人
			if(total==null || total == 0){
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
				return;
			}

			int b = 100;
			BigDecimal aBig = new BigDecimal(total);
			BigDecimal bBig = new BigDecimal(b);
			//向上取整
			Integer pages =   (int)Math.ceil(aBig.divide(bBig).doubleValue());

			for (int i = 0; i < pages; i++) {
				map3.put("page", i+1);
				map3.put("size", 100);
				Result result3 = humanClientService.PersonnelGetPersonInfo(map3);
				JSONObject jsonObject2  = JSON.parseObject(JSON.toJSONString(result3.getData()));

				String list =jsonObject2.get("list").toString();
				List<UserInfoYkmVo> userInfoYkmVos = JSON.parseArray(list, UserInfoYkmVo.class);

				for (UserInfoYkmVo userInfoYkmVo:userInfoYkmVos){
					//白名单人员全量
					if(request.getType()==1){
						Object roleI = redisUtil.hmGet("AreaAccess:"+request.getComId()+":areaNo:"+request.getAreaNo()+":time:"+request.getId(),userInfoYkmVo.getPId());
						//删除
						if(roleI==null){
							UserAccessPageSetAccessRequest request3 =new UserAccessPageSetAccessRequest();
							request3.setCompanyId(request.getComId());
							request3.setPId(userInfoYkmVo.getPId());
							request3.setUserId(userInfoYkmVo.getPId());
							request3.setAreaNo(request.getAreaNo());
							request3.setRoleI(0l);
							request3.setRegionId(0l);
							accessProductService.changeAccess(JSON.toJSONString(request3));
							continue;
						}
						//跳过
						Integer roleInt = (Integer) roleI;
						if(roleInt<0){
							continue;
						}
						UserAccessPageSetAccessRequest request3 =new UserAccessPageSetAccessRequest();
						request3.setCompanyId(request.getComId());
						request3.setPId(userInfoYkmVo.getPId());
						request3.setUserId(userInfoYkmVo.getPId());
						request3.setAreaNo(request.getAreaNo());
						request3.setRoleI(roleInt.longValue());
						request3.setRegionId(0l);
						accessProductService.changeAccess(JSON.toJSONString(request3));
						redisUtil.hmSet("AreaAccess:"+request.getComId()+":areaNo:"+request.getAreaNo()+":time:"+request.getId(),userInfoYkmVo.getPId(),-1);
						continue;
					}

					//未就餐统计
					if(request.getType()==2){
						if(ObjectUtil.isEmpty(request.getDate())){
							request.setDate(DateUtil.yesterday());
						}
						logger.info("==============进入未就餐统计,统计【{}】日未就餐数据,参数【{}】==============",DateUtil.formatDate(request.getDate()),humanMessage);
						Date yesterday = request.getDate();
						String dayStr = DateUtil.formatDate(yesterday);
//						List<Integer> mealNoList = new ArrayList<>();
//						mealNoList.add(2); //中餐
//						mealNoList.add(3); //晚餐

						ConsTimeConfigOnShowRequest configOnShowRequest = new ConsTimeConfigOnShowRequest();
						configOnShowRequest.setComId(request.getComId());
						Result mealTimeResult = this.payConfigClientService.GetMealTimeInfo(configOnShowRequest);

						if(mealTimeResult.getCode() != 200){
							continue;
						}
						JSONObject json= JSON.parseObject(JSON.toJSONString(mealTimeResult.getData()));
						logger.info(JSON.toJSONString(json.get("list")));
						List<GetMealTimeDto> mealTimeDtoList = JSON.parseArray(JSON.toJSONString(json.get("list")),GetMealTimeDto.class);
						if(ObjectUtil.isEmpty(mealTimeDtoList)){
							logger.info("未就餐统计：餐段信息为空【{}】",JSON.toJSONString(mealTimeDtoList));
							continue;
						}
//						Map<Integer,GetMealTimeDto> mealTimeDtoMap= new HashMap<>();
//						mealTimeDtoList.forEach(mealTime->{
//							mealTimeDtoMap.put(Integer.valueOf(mealTime.getMealNo()),mealTime);
//						});

						for (int j = 0; j < mealTimeDtoList.size(); j++) {

							GetMealTimeDto getMealTimeDto = mealTimeDtoList.get(j);
							Integer mealNo = Integer.valueOf(getMealTimeDto.getMealNo());
							if(ObjectUtil.isEmpty(getMealTimeDto)){
								logger.info("未就餐统计：餐段信息为空【{}】",JSON.toJSONString(getMealTimeDto));
								continue;
							}

							Date mealEndTime = DateUtil.parse(String.format("%s %s",dayStr,getMealTimeDto.getEndTime()), DatePattern.NORM_DATETIME_PATTERN);
							Date now = new Date();
							if(mealEndTime.after(now)){
								logger.info("未就餐统计：该餐段未结束，暂停统计,餐段信息：【{}】,时间：【{}】，参数：【{}】",JSON.toJSONString(getMealTimeDto),mealEndTime,humanMessage);
								continue;
							}

							GetOrderMealLeaveRequest getOrderMealLeaveRequest = new GetOrderMealLeaveRequest();
							getOrderMealLeaveRequest.setComId(userInfoYkmVo.getComId());
							getOrderMealLeaveRequest.setIsLeave(1);
							getOrderMealLeaveRequest.setBeginDate(dayStr);
							getOrderMealLeaveRequest.setEndDate(dayStr);
							getOrderMealLeaveRequest.setpId(userInfoYkmVo.getPId().intValue());
							getOrderMealLeaveRequest.setpCode(userInfoYkmVo.getPCode());
							getOrderMealLeaveRequest.setMealDate(yesterday);
							getOrderMealLeaveRequest.setMealNo(mealNo);
							getOrderMealLeaveRequest.setDeptId(userInfoYkmVo.getDeptId().intValue());
							Result result = payConfigClientService.getOrderMealLeave(getOrderMealLeaveRequest);
							if(result.getCode() == 200){
								JSONObject jsonObjectA = JSON.parseObject(JSON.toJSONString(result.getData()));
								List<EntityXfMealLeave> entityXfMealLeaves = JSON.parseArray(JSON.toJSONString(jsonObjectA.get("list")), EntityXfMealLeave.class);
								if(ObjectUtil.isNotEmpty(entityXfMealLeaves)){
									logger.info("人员请假");
									continue;
								}
								EntityNotMealRecode entityNotMealRecode = new EntityNotMealRecode();
								entityNotMealRecode.setMealDate(yesterday);
								entityNotMealRecode.setMealNo(mealNo.toString());
								entityNotMealRecode.setDeptId(userInfoYkmVo.getDeptId());
								entityNotMealRecode.setPid(userInfoYkmVo.getPId());
								entityNotMealRecode.setComId(userInfoYkmVo.getComId());
								entityNotMealRecode.setPCode(userInfoYkmVo.getPCode());
								entityNotMealRecode.setDeptName(userInfoYkmVo.getDeptName());
								entityNotMealRecode.setPName(userInfoYkmVo.getPName());
								Result result1 = this.xfRecordFeign.saveNotMealRecode(entityNotMealRecode);
								logger.info("就餐统计返回结果：参数：{},结果：{}",JSON.toJSONString(entityNotMealRecode),JSON.toJSONString(result1));
							}
						}


//						EntityMjKaoqin entityMjKaoqin=new EntityMjKaoqin();
//						entityMjKaoqin.setComId(request.getComId());
//						entityMjKaoqin.setPId(userInfoYkmVo.getPId());
//						entityMjKaoqin.setDeptId(userInfoYkmVo.getDeptId());
//						entityMjKaoqin.setAreaId(userInfoYkmVo.getRegionId());
//						entityMjKaoqin.setState(userInfoYkmVo.getRegionOnline());
//						humanClientService.saveUserRegion(entityMjKaoqin);
					}

				}
			}


//			if(request.getType()==2){
//				//查找人数
//				for (int i = 0 ;i<10; i++){
//					UserAccessPageSetAccessRequest request3 =new UserAccessPageSetAccessRequest();
//					request3.setCompanyId(1l);
//					request3.setPId(2565l);
//					request3.setAreaNo(40l);
//					request3.setRoleI(1l);
//					accessProductService.changeAccess(JSON.toJSONString(request3));
//				}
//			}

		} catch (Exception e) {
			e.printStackTrace();

			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			return;
		}
		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		logger.info("AllPerson-end:【{}】",humanMessage);
		logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());
	}

	/**
	 * 把该监听命名为B监听
	 * 监听死信队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues =  AllPersonConfig.ALL_PERSON_DIE_QUEUE)
	public void processForDie(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		//死信队列放弃
		channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
	}


}
